
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:getxx/const.dart';
import 'package:getxx/widgets/gallery.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class PostEditPage extends StatefulWidget {
  const PostEditPage({super.key});

  @override
  State<PostEditPage> createState() => _PostEditPageState();
}

class _PostEditPageState extends State<PostEditPage> {

  //主视图
  Widget _mainView(){
    return Column(children: [

      //图片列表
      _buildPhotosList(),
      // const Spacer(),
      // //底部删除bar
      // isDragNow ? _buildRemoveBar() : SizedBox.shrink() ,
    ],);
  }
  //已选中的图片列表
 List<AssetEntity>  _selectedAssets =[];
  //是否开始拖拽
  bool isDragNow = false;
  //是否将要删除
  bool isWillRemove =false ;


  //图片列表
  Widget _buildPhotosList(){
    return Padding(padding: EdgeInsets.all(spacing),
    child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints){
      final double width = (constraints.maxWidth - spacing *2 )/3;
      return     Wrap(
        spacing: spacing,
        runSpacing: spacing,
        children: [
          //图片列表
          for(final asset in _selectedAssets)
             _buildPhotoItem(asset, width),
          //加入按钮
          if(_selectedAssets.length<maxAssets)
            //添加图片按钮
           _buildAddBtn(context, width),
        ],
      );

    }),);
  }

  GestureDetector _buildAddBtn(BuildContext context, double width) {
    return GestureDetector(
           onTap: () async {
             final List<AssetEntity>? result = await AssetPicker.pickAssets(context,
                 pickerConfig: AssetPickerConfig(
                   selectedAssets: _selectedAssets,
                 ));
             if(result == null) return ;
             setState(() {
               _selectedAssets = result;
             });
           },
           child:Container(
             color: Colors.black12,
             width: width,
             height: width,
             child: Icon(Icons.add,size: 48,color: Colors.black38,),
           ),

         );
  }

  //删除bar
  Widget _buildRemoveBar(){
    return DragTarget(builder: ( context,  candidateData, rejectedData){
      return Container(
        height: 150,
        width: MediaQuery.of(context).size.width,
        color: isWillRemove ? Colors.pink[500] : Colors.pink[300],
        child:  Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            //图标
            Icon(Icons.delete,size: 40,
              color: isWillRemove ? Colors.white : Colors.white70,),
            //文字
            Text('垃圾箱',style: TextStyle(
              color: isWillRemove ? Colors.white : Colors.white70
            ),)
          ],
        ),
      );
    },
        //调用以确定此小部件是否有兴趣接收给定的 将数据拖到此拖动目标上。
      onWillAcceptWithDetails:(data){
      setState(() {
        isWillRemove = true;
      });
      return true;
    } ,
      //当可接受的数据片段被丢弃在此拖动目标上时调用。 如果 是 ，则不会调用它。datanull
      onAcceptWithDetails: (data){
       setState(() {
         _selectedAssets.remove(data);
         isWillRemove =false;
       });
      },

      //当拖动到目标上的给定数据离开时调用目标
      onLeave: (data){
       setState(() {
         isWillRemove =false;
       });
      },
    );
  }

  Widget _buildPhotoItem(AssetEntity asset, double width) {
    return Draggable(
      //可以拖动对象将拖放的数据
      data: asset,
      //当可拖动对象开始拖动时调用
        onDragStarted: (){
        setState(() {
          isDragNow =true;
        });
      },
        //当拖动对象被放下时调用
        onDragEnd: (details){
        setState(() {
          isDragNow =false;
        });
        },
        //当draggable 被放置并被【DragTarget】接收的时候调用
        onDragCompleted: (){

        },
        //当darggable 被放置但未被【DragTarget】接收时调用
        onDraggableCanceled: (Velocity, Offset){

        },

      //拖动进行时显示在指针下面的小部件
        feedback: Container(

     clipBehavior: Clip.antiAlias,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10)
          ),

          child: AssetEntityImage(
            asset,
            width: width,
            height: width,
            fit: BoxFit.cover,
            isOriginal: false,
          ),
    ),

        //当你正在拖拽的时候 显示的是小部件
        childWhenDragging: Container(

          clipBehavior: Clip.antiAlias,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10)
          ),

          child: AssetEntityImage(
            asset,
            width: width,
            height: width,
            fit: BoxFit.cover,
            isOriginal: false,
            opacity: const AlwaysStoppedAnimation(0.2),
          ),
        ),
        //子组件
        child: GestureDetector(
      onTap: () => {
        Navigator.push(context, MaterialPageRoute(builder: (context){
          return GalleryWidget(initialIndex: _selectedAssets.indexOf(asset), items: _selectedAssets);
        }))
      },
      child: Container(
        clipBehavior: Clip.antiAlias,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.0),),child:  AssetEntityImage(
        asset,
        height:width,
        width: width,
        fit: BoxFit.cover,
        isOriginal: false, //是否原图
      ),

      ),
    ));
  }

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      appBar: AppBar(
        title: const Text('发布', ),
          backgroundColor: weChatThemeColor,
        centerTitle: true,
      ),
      body: _mainView(),
      bottomSheet: isDragNow ? _buildRemoveBar() : null ,
    );
  }
}
